<?php

namespace app\service;

use app\model\BookType;
use exception;
use teamones\Request;
use app\model\Member as MemberModel;
use app\model\Post as PostModel;
use app\model\PostRecord as PostRecordModel;
use support\ErrorCode;
use Yurun\Util\YurunHttp\Http\Response;

class Member
{

    /**
     * 查询成员权限
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMemberInfo(array $params): array
    {
        // 获取租户id
        $memberService = new Member();
        $memberData = $memberService->getTenantInfo($params['tenant_id'], 'id,created_by');
        // 租户创建人
        $tenantCreatedBy = $memberData['data']['created_by'] ?? 0;

        $superAdmin = [];
        // 如果是超级管理员
        if ($tenantCreatedBy == $params['user_id']) {
            $superAdmin = $this->getSuperInfo($params);
        }
        $memberModel = MemberModel::where(['type' => $params['type'], 'type_id' => $params['type_id'], 'tenant_id' => $params['tenant_id']]);
        if (!empty($params['page'])) {
            $page = $params['page'] ?? [1, 10];
            $memberModel = $memberModel->page($page[0], $page[1]);
        }
        $memberModel = $memberModel->select();
        $data = [];
        if (!$memberModel->isEmpty()) {
            $data = $memberModel->toArray();
        }
        $returnData = [];
        if (!empty($data)) {

            $allUid = array_column($data, 'user_id');           // 所有用户id
            if (!empty($allUid)) {
                $userInfo = $this->getUserInfo($allUid); // 获取用户信息
            }
            if (empty($userInfo)) {
                return [];
            }
            $userInfoId = array_column($userInfo['data']['rows'], null, 'id');
            foreach ($data as $k => $v) {
                $returnData[$k]['id'] = $v['id'];
                $returnData[$k]['role'] = $v['role'] ?? '';
                $returnData[$k]['name'] = $userInfoId[$v['user_id']]['name'] ?? '';
                $returnData[$k]['avatar'] = $userInfoId[$v['user_id']]['avatar'] ?? '';
                $returnData[$k]['user_id'] = $v['user_id'];
            }
        }
        return array_merge($superAdmin, $returnData);
    }


    /**
     * 获取当前用户角色
     * @param $type
     * @param $typeId
     * @param $params
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNowUserPer($type, $typeId, $params)
    {
        // 如果是超级管理员
        if ($params['tenantCreateById'] == $params['user_id']) {
            return 'super_admin';
        }
        // 知识库
        if ($type == 'knowledge') {
            // 匹配权限列表
            $perModel = MemberModel::where(['type' => $type, 'type_id' => $typeId, 'user_id' => $params['user_id'], 'tenant_id' => $params['tenant_id']])->find();
            if (!empty($perModel)) {
                $perData = $perModel->toArray();
                return $perData['role'] ?? 'viewer';
            }
            // 查询当前知识库是否当前当前用户创建
            $res = BookType::where(['id' => $typeId, 'created_by' => $params['user_id']])->value('id');
            if ($res) {
                return 'super_admin'; // 超级管理员
            }
        }
        // 知识本,会话
        if ($type == 'book' || $type == 'chat') {
            $bookType = BookType::where(['id' => $params['book_type_id']])->value('type');
            // 如果是平台级,返回普通角色,只有查看权限
            if ($bookType == BookType::PLATFORM_BOOK_TYPE) {
                return 'viewer';
            }
            // 匹配权限列表
            $perModel = MemberModel::where(['type' => $type, 'type_id' => $typeId, 'user_id' => $params['user_id'], 'tenant_id' => $params['tenant_id']])->find();
            if (!empty($perModel)) {
                $perData = $perModel->toArray();
                return $perData['role'] ?? 'viewer';
            }
            // 继承知识库权限
            $perModel = MemberModel::where(['type' => 'knowledge', 'user_id' => $params['user_id'], 'tenant_id' => $params['tenant_id']])->find();
            if (!empty($perModel)) {
                $perData = $perModel->toArray();
                return $perData['role'] ?? 'viewer';
            }
            // 如果是文档创建者
            $postModel = PostModel::where(['id' => $typeId, 'created_by' => $params['user_id'], 'tenant_id' => $params['tenant_id']])->find();
            if ($postModel) {
                return 'super_admin';
            }
            // 如果是知识库的创建者
            $res = BookType::where(['id' => $typeId, 'created_by' => $params['user_id']])->value('id');
            if ($res) {
                return 'super_admin';
            }
        }
        return 'viewer';
    }

    /**
     * 获取用户信息
     * @param array $id
     * @return array|mixed|void|Response
     * @throws exception
     */
    public function getUserInfo(array $id)
    {
        if (empty($id)) {
            return [];
        }
        try {
            $result = Request::connection()
                ->setHeader([
                    'X-Userinfo' => request()->getXUserInfo(),
                ])
                ->setServerHost('teamones-im')
                ->setRoute('user/select')
                ->setBody([
                    "param" => [
                        "filter" => [
                            "id" => ['-in', join(',', $id)],
                        ],
                        "fields" => 'id,name,email,phone,sex,last_online_time,unionid,active'
                    ]
                ])
                ->setMethod()
                ->request();
            if (!empty($result)) {
                return $result;
            }
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), ErrorCode::GET_IM_USER_INFO_FAILURE);
        }
    }

    /**
     * 更新权限
     * @return bool|void
     * @throws exception
     */
    public function update($params)
    {
        //  查询当前用户是否有权限
        $id = MemberModel::where(['type_id' => $params['type_id'], 'user_id' => $params['user_id'], 'type' => $params['type'], 'tenant_id' => $params['tenant_id']])
            ->value('id');
        $member = new MemberModel();
        try {
            // 有权限更新新的权限
            if (isset($id)) {
                $member->where('id', $id)->update(['role' => $params['role']]);
                return $id;
            }
            // 没有权限增加新的权限
            $member->data([
                'role' => $params['role'],
                'type' => $params['type'],
                'type_id' => $params['type_id'],
                'user_id' => $params['user_id'],
                'tenant_id' => $params['tenant_id'],
            ]);
            if ($member->save()) {
                return $member->getPk();
            }
            return false;
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), ErrorCode::UPDATE_PER_FAILURE);
        }
    }

    /**
     * 删除权限
     * @param $filter
     * @throws \Throwable
     */
    public function delete($filter)
    {
        $data = MemberModel::where(['id' => $filter['id']])->field('id')->select();
        if (!empty($data)) {
            $deleteId = $data->column('id');
            MemberModel::whereIn('id', $deleteId)->delete();
        }
    }

    /**
     * 创建权限
     * @param $data
     * @return \think\Collection|void
     * @throws \Throwable
     */
    public function create($data)
    {
        $modelModel = new MemberModel();
        $saveData = [];
        $users = array_unique($data['users']);
        // 过滤已经有权限的用户
        $users = $this->filterUsersPer($users, $data);
        if (!empty($users)) {
            foreach ($users as $k => $v) {
                $saveData[$k]['type'] = $data['type'];
                $saveData[$k]['role'] = $data['role'];
                $saveData[$k]['type_id'] = $data['type_id'];
                $saveData[$k]['user_id'] = $v;
                $saveData[$k]['tenant_id'] = $data['tenant_id'];
            }
            return $modelModel->saveAll($saveData);
        }
    }


    /**
     * 获取默认超级管理员数据
     * @param $param
     * @return array[]|void
     * @throws exception
     */
    public function getSuperInfo($param)
    {
        try {
            $userInfo = $this->getUserInfo([$param['user_id']]);
            return [
                [
                    'id' => 0,
                    'role' => 'super_admin',
                    'name' => $userInfo['data']['rows'][0]['name'],
                    'avatar' => $userInfo['data']['rows'][0]['avatar'],
                    'user_id' => $param['user_id']
                ]
            ];
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), ErrorCode::GET_IM_USER_INFO_FAILURE);
        }
    }

    /**
     * 获取租户信息
     * @param int $tenantId
     * @param string $fields
     * @return array|mixed|void|Response
     * @throws exception
     */
    public function getTenantInfo(int $tenantId, string $fields = '*')
    {
        try {
            $result = Request::connection()
                ->setHeader([
                    'X-Userinfo' => request()->getXUserInfo(),
                ])
                ->setServerHost('teamones-im')
                ->setRoute('tenant/find')
                ->setBody([
                    "param" => [
                        "filter" => [
                            "id" => $tenantId
                        ],
                        "fields" => $fields
                    ]
                ])
                ->setMethod()
                ->request();
            return $result ?? [];
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), ErrorCode::GET_IM_TENANT_INFO_FAILURE);
        }
    }


    /**
     * 过滤已经存在权限的用户
     * @param $users
     * @param $data
     * @return array
     * @throws exception
     */
    public function filterUsersPer($users, $data): array
    {
        $memberUserId = MemberModel::where(['type' => $data['type'], 'user_id' => $data['users'], 'type_id' => $data['type_id'], 'tenant_id' => $data['tenant_id']])
            ->field('type,user_id,type_id')->column('user_id');
        // 过滤已有权限的用户
        if (!empty($memberUserId)) {
            $users = array_diff($users, $memberUserId);
        }
        // 过滤聊天创建者
        if ($data['type'] == 'chat') {
            $postRecordModel = new PostRecordModel();
            $bookCreatedUserId = $postRecordModel->where(['id' => $data['type_id'], 'user_id' => $data['users'], 'tenant_id' => $data['tenant_id']])
                ->field('user_id')->column('user_id');
            // 忽略给建人赋予权限
            if (!empty($bookCreatedUserId)) {
                $users = array_diff($users, $bookCreatedUserId);
            }
        }
        // 过滤知识本创建者
        if ($data['type'] == 'book') {
            $postModel = new PostModel();
            $postCreatedUserId = $postModel->where(['id' => $data['type_id'], 'created_by' => $data['users'], 'tenant_id' => $data['tenant_id']])
                ->field('created_by')->column('created_by');
            if (!empty($memberUserId)) {
                $postCreatedUserId = array_unique(array_merge($postCreatedUserId, $memberUserId));
            }
            // 忽略创建人赋予权限
            if (!empty($postCreatedUserId)) {
                $users = array_diff($users, $postCreatedUserId);
            }
        }
        // 过滤掉超级用户
        if (!empty($data['tenant_id'])) {
            // 获取租户id
            $memberService = new Member();
            $memberData = $memberService->getTenantInfo($data['tenant_id'], 'id,created_by');
            $tenant_id = (int)$memberData['data']['created_by'] ?? 0;
            $users = array_diff($users, [$tenant_id]);
        }
        return $users;
    }

}
